import Request from "luch-request";
import {
	baseUrl,
	type
} from "./app.js"
import {
	Secret,
	getTimeStamp
} from "@/common/utils/secret.js";

const getTokenStorage = () => {
	let token = "";
	try {
		token = uni.getStorageSync("token");
	} catch (e) {}
	return token;
};

const http = new Request();

/* 设置全局配置 */
http.setConfig((config) => {
	config.header = {
		...config.header,
	};
	config.sslVerify = false
	// #ifdef H5
	config.baseURL = '/'
	// #endif
	// #ifndef H5
	config.baseURL = baseUrl
	// #endif
	// 自定义的配置
	config.custom = {
		auth: true, // 是否传token
	};
	return config;
});

http.interceptors.request.use(
	async (config) => {
			config.header = {
				...config.header,
				"token": getTokenStorage(),
				// "X-Requested-Token": getTokenStorage(),
				// "locale": uni.getStorageSync('language') || 'zh_CN'
			}
			// console.log(config,'config')
			// get请求不需要加密
			if (config.method === 'POST' && type) {
				let urls = ['/api/user/upload', '/api/upload/upFile']
				//图片上传接口不需要加密
				if (!urls.includes(config.url)) {
					//同步请求 获取时间戳
					await getTimeStamp().then(res => {
						config.data.vtime = res;
						config.data = {
							data: Secret.encrypt(JSON.stringify(config.data))
						};
					})
				}
			}
			return config;
		},
		(config) => {
			return Promise.reject(config);
		}
);

http.interceptors.response.use(
	(response) => {
		// console.log('解密', response);
		// 解密
		if (response.data.code == 1) {
			if (!Array.isArray(response.data.data) && response.data.data != null && response.data != []) {
				// console.log(666, JSON.parse(Secret.decrypt(response.data.data)));
				if (type) {
					response.data.data = JSON.parse(Secret.decrypt(response.data.data));
				}
			}
		}
		if (response.data.code == 401 || response.data.code == 10) {
			// console.log('401401401401401401401401401401');
			// let path = 'loginWeixin'
			// // #ifdef APP-PLUS
			// path = 'login'
			// // #endif
			uni.navigateTo({
				url: "/pages/login/login/loginWeixin",
			});
		}
		return response;
	},
	(response) => {
		/*  对响应错误做点什么 （statusCode !== 200）*/
		// console.log('对响应错误做点什么', response);
		if (response.data.code == 401 || response.data.code == 10) {
			let path = 'loginWeixin'
			// #ifdef APP-PLUS || H5
			path = 'login'
			// #endif
			uni.navigateTo({
				url: "/pages/login/login/" + path,
			});
			uni.showToast({
				title: '请登录',
				icon:"none"
			})
		}
		if (response.statusCode == 500) {
			uni.showToast({
				icon: 'error',
				title: '服务器错误'
			})
		}
		return Promise.reject(response);
	}
);

export default http